<?php
namespace api\modules\v1\models\user;

use api\modules\v1\models\circle\Circle;
use api\modules\v1\models\circle\CircleUserRelation;
use api\modules\v1\models\Common;
use api\modules\v1\models\friend\Friend;
use api\modules\v1\models\group\Group;
use api\modules\v1\models\group\GroupUser;
use api\modules\v1\models\redPacket\RedPacket;
use api\modules\v1\models\redPacket\RedPacketLog;
use api\modules\v1\models\shop\GoodsInfo;
use api\modules\v1\models\shop\GoodsOrder;
use api\modules\v1\models\userLevel\UserLevel;
use common\models\CacheKeys;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\im\Im;
use common\models\im\ImQrcode;
use common\models\Status;
use common\models\user\UserUnusualLog;
use common\models\user\UserViewLog;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\StringHelper;

class User extends \api\modules\common\models\User
{

    /**
     * 获取userSig
     * @return array
     */
    public function getSig() {
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
//            $user = $this->checkUser();

            $sigStr = (new Im()) ->imSignatureGeneration($user['tx_code'],60*60*24*7);

            $config = static::getCommonByKey(['money_user_id','system_user_id']);

            $data = [
                'tx_code' => $user['tx_code'],
                'user_sig' => $sigStr,
                'money_user' => $config['money_user_id'] ?? '',
                'system_user' => $config['system_user_id'] ?? '',
            ];

            // 未读数量
            FriendApply::notReadApplyNum($user['id']);
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取用户基本信息
     * @return array
     */
    public function getInfo()
    {
        try {

            $user = Yii::$app->getUser()->getIdentity()->toArray();

//            $user = $this->checkUser();
            $redPacketLogModel = new RedPacketLog();
            $redPacketModel = new RedPacket();

            //圈子相关
            $circleWhere['user_id'] = $user['id'];
            $circleWhere['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $circleWhere['status'] = Status::COMMON_CHECKING_SUCCESS;
            $circleWhere['is_see'] = Status::COMMON_RADIO_YES;
            $collect_num = (int)Circle::getSumByWhere($circleWhere,'collect_num')?:0;

            // 圈子获赞数量
            $circleLikeNum = (int)CircleUserRelation::getCountByWhere(['topic_user_id'=>$user['id'],'type'=>Status::CIRCLE_USER_RELATION_TYPE_LIKE])?:0;
            // 粉丝数量
            $fansNum = (int)UserAttention::getCountByWhere([
                'topic_id'=>$user['id'],'type'=>Status::USER_ATTENTION_TYPE_FOLLOW,'is_together' => Status::COMMON_RADIO_NO
            ])?:0;
            // 关注数量
            $attentionNum = (int)UserAttention::getCountByWhere([
                'user_id'=>$user['id'],'type'=>Status::USER_ATTENTION_TYPE_FOLLOW,'is_together' => Status::COMMON_RADIO_NO
            ])?:0;

            // 收藏圈子数量
            $userCollect = CircleUserRelation::getCountByWhere(['user_id'=>$user['id'],'type'=>Status::CIRCLE_USER_RELATION_TYPE_COLLECT])?:0;
            // 谁看过我
            $viewNum = UserViewLog::getCountByWhere(['view_user'=>$user['id']])?:0;

            // 商户信息
            $businessInfo = UserBusiness::getOneByWhere(['user_id'=>$user['id']]);

            // 我买的商品数量
            $buyOrderNum = (int) GoodsOrder::getSumByWhere(['user_id' => $user['id'],
                'status' => [
                    Status::USER_GOODS_ORDER_STATUS_WAITING_PAY,
                    Status::USER_GOODS_ORDER_STATUS_WAITING_SEND,
                    Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE,
                    Status::USER_GOODS_ORDER_STATUS_DONE,
                ],
                'is_delete' => Status::COMMON_IS_NOT_DELETE,
                'is_read' => Status::COMMON_RADIO_NO
            ], 'num');

            // 我卖的数量
            $sellOrderNum = (int) GoodsOrder::getSumByWhere(['sell_user' => $user['id'],
                'status' => [
                    Status::USER_GOODS_ORDER_STATUS_WAITING_SEND,
                    Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE,
                    Status::USER_GOODS_ORDER_STATUS_DONE,
                ],
                'is_delete' => Status::COMMON_IS_NOT_DELETE,
                'business_is_read' => Status::COMMON_RADIO_NO
            ], 'num');

            # 我发布的数量
            $myGoodsNUm = (int) GoodsInfo::getCountByWhere(['user_id' => $user['id'],'status' => [
                Status::COMMON_RADIO_YES
            ]]);
            //谁加我
            $applyWhere['status'] = Status::COMMON_CHECKING_WAITING;
            $applyWhere['friend_id'] = $user['id'];
            $applyNum = FriendApply::getCountByWhere($applyWhere);

            // 级别
            $level = UserLevel::getOneByWhere(['id' => $user['level_id']]);
            $data = [
                'id' => $user['id'],
                'tx_code' => $user['tx_code'],
                'user_code' => $user['user_code'],
                'qr_code' => static::getImages($user['qr_code']),
                "face" => static::getAvatar($user['user_face']),
                'signature' => $user['signature'] ?: '暂无个性签名',
                'nick_name' => StringHelper::truncate($user['nick_name'], 12),
                'phone' => Functions::hiddenPhone($user['login_name'], 3, 4),
                'is_kyc' => (int) $user['is_kyc'],
                'kyc' => (int) Status::COMMON_RADIO_NO,
                'pay_password' => (int) (empty($user['pay_password']) ? Status::COMMON_RADIO_NO : Status::COMMON_RADIO_YES),
                'sex' => (int) $user['sex'],
                'birthday' => $user['birthday'] ?: '',
                'height' => $user['height'] ? $user['height'].'CM' : '未知',
                'money_switch' => (int) $user['money_switch'],
                'money' => $user['money'],
                'coin' => $user['coin'],
                'shop_money' => $user['shop_money'],
                # 是否是商家
                'is_service' => $user['is_service'] == Status::COMMON_RADIO_YES,
                #兴趣爱好
                'interests' => array_filter(explode(',',trim($user['interests'],','))),
                # 是否隐身
                'is_hiding' => $user['is_hiding'] == Status::COMMON_RADIO_YES,

                # 级别信息
                'is_level' => (boolean) ($user['is_level'] == Status::COMMON_RADIO_YES),
                'level_id' => (int) $user['level_id'],
                'level_expire_time' => (string) $user['level_expire_time'],
                'level_name' => (string) $level['name'] ?: '未开通',

                // 收到红包信息
                'receive_red_packet_money' => floatval($redPacketLogModel::getSumByWhere(['receive_user_id' => $user['id']],'receive_money')),
                'receive_red_packet_number' => floatval($redPacketLogModel::getCountByWhere(['receive_user_id' => $user['id']])),

                // 发送红包信息
                'send_red_packet_money' => floatval($redPacketModel::getSumByWhere(['user_id' => $user['id']],'money')),
                'send_red_packet_number' => floatval($redPacketModel::getCountByWhere(['user_id' => $user['id']])),

                // 个人隐私设置
                'is_search_code' => (int) $user['is_search_code'],
                'is_search_phone' => (int) $user['is_search_phone'],
                'is_add_friend_by_qr_code' => (int) $user['is_add_friend_by_qr_code'],
                'is_add_friend_by_business_card' => (int) $user['is_add_friend_by_business_card'],
                'is_login_by_code' => (int) $user['is_login_by_code'],
                // 是否自动进群
                'is_auto_enter_group' => (int) $user['is_auto_enter_group'],

                //关注
                'attention_num' => $attentionNum,
                'fans_num' => $fansNum,
                //圈子相关
                'circle_num' => (int)Circle::getCountByWhere($circleWhere),
                'circle_like_num' => $circleLikeNum,
                'circle_collect_num' => $collect_num,
                'circle_all_num' => bcadd($circleLikeNum,$collect_num),
                //收藏数量
                'user_collect_num' => $userCollect,
                //谁看过我
                'view_num' => $viewNum,
                'business_info' => $businessInfo ? true : false,

                # 我买到的商品数量
                'buy_num' => $buyOrderNum,

                # 我卖出的数量
                'sell_num' => $sellOrderNum,

                # 我发布的商品数量
                'goods_num' => $myGoodsNUm,
                'apply_num' => $applyNum,

            ];


            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    // 获取当前用户级别信息
    public function getUserLevelInfo() {
        try {

            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $data = [];
            $currentLevelInfo = UserLevel::getOneByWhere(['id' => $user['level_id']]);

            $data['video_duration_limit'] = $currentLevelInfo['video_duration_limit'];  #朋友圈和橱窗上传视频限制
            $data['circle_word_limit'] = $currentLevelInfo['circle_word_limit'];
            $data['goods_word_limit'] = $currentLevelInfo['goods_word_limit'];

            return Functions::formatRestAPI(0, '', $data);
        }
        catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        }
        catch (Exception $e) {
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        }
    }

    /**
     * 保存用户信息
     * @return array
     */
    public function saveInfo()
    {
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();

            $data = [];
            $signature = Yii::$app->request->post('signature','');
            $face = Yii::$app->request->post('face','');
            $nickName = Yii::$app->request->post('nick_name','');

            $isSearchCode = Yii::$app->request->post('is_search_code','');
            $isSearchPhone = Yii::$app->request->post('is_search_phone','');
            $isAddFriendByQrCode = Yii::$app->request->post('is_add_friend_by_qr_code','');
            $isAddFriendByBusinessCard = Yii::$app->request->post('is_add_friend_by_business_card','');
            $isLoginByCode = Yii::$app->request->post('is_login_by_code','');

            #新用户设置
            $newSetting = Yii::$app->request->post('new_setting',0);
            $sex = Yii::$app->request->post('sex',0);
            $birthday = Yii::$app->request->post('birthday','');
            $interests = Yii::$app->request->post('interests',[]);

            $height = Yii::$app->request->post('height',0);
            if ($height) {
                $data['height'] = $height;
            }

            # 是否自动进群设置
            $isAutoEnterGroup = Yii::$app->request->post('is_auto_enter_group',''); # 是否自动进群
            if ($isAutoEnterGroup) {
                if (!in_array($isAutoEnterGroup,[1,2])) {
                    throw new Exception('是否自动进群参数有误');
                }
                $data['is_auto_enter_group'] = (int) $isAutoEnterGroup;
            }

            # 隐身设置
            $isHiding = Yii::$app->request->post('is_hiding',0);
            if ($isHiding) {
                $data['is_hiding'] = (int) $isHiding;
            }

            if ($newSetting) {
                $data['is_setting'] = Status::COMMON_RADIO_YES;
                if (!$nickName || !$sex || !$birthday || !$interests) {
                    throw new Exception('请补全信息');
                }
            }

            if ($sex) {
                $data['sex'] = (int) $sex;
            }

            if ($birthday) {
                $data['birthday'] = date('Y-m-d',strtotime($birthday));
            }

            if ($interests) {
                //格式  1,2,
                $data['interests'] = trim(implode(',',$interests),',').',';
            }

            if ($signature) {
                $data['signature'] = $signature;

                // 更新用户信息
                $updateImUser['Tag_Profile_IM_SelfSignature'] = $signature;
                $resIm = (new Im()) -> updateUser($user['tx_code'], $updateImUser);
                if (!$resIm) {
                    throw new Exception('更新用户信息失败');
                }
            }


            if ($face) {
                $data['user_face'] = $face;
                $imUserFace = static::getImages($face);

                $qrCode = (new ImQrcode())->userQrCode($user['id'], $user['tx_code'], $imUserFace);
                $data['qr_code'] = $qrCode;

                // 更新用户信息
                $updateImUser['Tag_Profile_Custom_Qrcode'] = static::getImages($qrCode);
                $updateImUser['Tag_Profile_IM_Image'] = static::getAvatar($imUserFace);
                $resIm = (new Im()) -> updateUser($user['tx_code'], $updateImUser);
                if (!$resIm) {
                    throw new Exception('更新用户信息失败');
                }
            }

            if ($nickName) {
                $check = static::getOneByWhere(['nick_name' => $nickName]);
                if ($check) {
                    throw new Exception('该昵称被使用了，请重新输入');
                }
                $data['nick_name'] = $nickName;
                // 更新用户信息
                $updateImUser['Tag_Profile_IM_Nick'] = $nickName;
                $resIm = (new Im()) -> updateUser($user['tx_code'], $updateImUser);
                if (!$resIm) {
                    throw new Exception('更新用户信息失败');
                }
            }

            if ($isSearchCode) {
                $data['is_search_code'] = $isSearchCode;
            }

            if ($isSearchPhone) {
                $data['is_search_phone'] = $isSearchPhone;
            }

            if ($isAddFriendByQrCode) {
                $data['is_add_friend_by_qr_code'] = $isAddFriendByQrCode;
            }

            if ($isAddFriendByBusinessCard) {
                $data['is_add_friend_by_business_card'] = $isAddFriendByBusinessCard;
            }

            if ($isLoginByCode) {
                $data['is_login_by_code'] = $isLoginByCode;
            }

            $res = static::updateData($data, ['id' => $user['id']]);
            if ($res === false) {
                throw new Exception('系统繁忙，请稍后再试');
            }

            return Functions::formatRestAPI(0, '修改成功', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 用户列表
     * @return array
     */
    public function getList()
    {
        try{
            $page = (int) Yii::$app->request->post('page',1);
            $size = (int) Yii::$app->request->post('size',20);
            $account = (string) Yii::$app->request->post('account','');

            $where = $andWhere = [];
            $where['is_delete'] = Status::COMMON_RADIO_YES;
            $where['status'] = Status::COMMON_RADIO_YES;
            if (!empty($account)) {
                $andWhere[] = ['or',
                    ['and',['=','user_code',$account],['=','is_search_code',Status::COMMON_RADIO_YES]],
                    ['and', ['=','phone',$account],['=','is_search_phone',Status::COMMON_RADIO_YES]],
                    ['=','tx_code',$account],
                ];

            } else {
                $data = [
                    'total' => 0,
                    'page' => 1,
                    'totalPage' => 0,
                    'data' => [],
                ];
                return Functions::formatRestAPI(0, '', $data);
            }

            $count = static::getCountByAndWhere($where,$andWhere);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where,$andWhere, ['id','nick_name','user_face','tx_code','qr_code','signature','is_auto_enter_group'], 'id DESC', $offset, $size)->with()->asArray()->all();
            $result = [];
            foreach ($list as $v) {
                $result[] = [
                    'id' => (int) $v['id'],
                    'nick_name' => $v['nick_name'] ?? '',
                    'face' => static::getAvatar($v['user_face']),
                    'tx_code' => $v['tx_code'],
                    'qr_code' => static::getImages($v['qr_code']),
                    'signature' => $v['signature'],
                    'is_auto_enter_group' => $v['is_auto_enter_group'] ?? Status::COMMON_RADIO_NO,
                ];
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 根据txcode获取用户信息
     * @return array
     */
    public function getTxInfo()
    {
        try {

            $txCode = Yii::$app->request->get('txcode','');
            if(empty($txCode)){
                throw new Exception('参数错误');
            }

            $user = static::getOneByWhere(['tx_code' => $txCode]);
            if ($user['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('该账号已被封禁，请联系管理员');
            }
            if($user == false){
                throw new Exception('未知信息');
            }

            $data = [
                'id' => $user['id'],
                'tx_code' => $user['tx_code'],
                'user_code' => $user['user_code'],
                "nick_name" => $user['nick_name'],
                'qr_code' => static::getImages($user['qr_code']),
                "face" => static::getAvatar($user['user_face']),
                'signature' => $user['signature'],
                'is_auto_enter_group' => $user['is_auto_enter_group'] ?? Status::COMMON_RADIO_NO,

            ];

            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 发送名片
     * @return array
     */
    public function sendBusinessCard() {
        $redis = Yii::$app->redis;

        $user = Yii::$app->getUser()->getIdentity()->toArray();
        $userId = $user['id'];
        $trans = static::getDb()->beginTransaction();
        try {
            if (!$userId) {
                throw new Exception('未知用户！');
            }

            $type = Yii::$app->request->post('type',0); // 1-单聊发名片 2-群聊发名片
            $receiveTxCode = Yii::$app->request->post('receive_tx_code',''); // 接受的群或者接收的用户 tx_code
            $sendTxCode = Yii::$app->request->post('send_tx_code',''); // 好友的tx_code

            if(!in_array($type, array_keys(Status::IM_BUSINESS_CARD_SEND_TO_MAP))) {
                throw new Exception('名片类型不合法！');
            }

            if(!$receiveTxCode) {
                throw new Exception('接收方账号不能为空！');
            }

            if(!$sendTxCode) {
                throw new Exception('发送的名片不能为空！');
            }

            $businessCardUserInfo = User::getOneByWhere(['tx_code' => $sendTxCode]);
            if (!$businessCardUserInfo) {
                throw new Exception('发送的名片不能为空!');
            }

            $exists = $redis->get(CacheKeys::IM_SEND_BUSINESS_CARD . $userId);
            if($exists){
                throw new Exception('您的速度太快了！');
            }
            $redis->set(CacheKeys::IM_SEND_BUSINESS_CARD . $userId, true);

            if ($type == Status::IM_BUSINESS_CARD_SEND_TO_USER) {
                // 单聊名片
                $sendUser = User::getOneByWhere(['tx_code' => $receiveTxCode]);
                if (empty($sendUser)) {
                    throw new Exception("该用户不存在！");
                }

                $userFriendInfo = Friend::getOneByWhere([
                    'user_id' => $userId,
                    'friend_id' => $sendUser['id'],
                ]);

                if (empty($userFriendInfo)) {
                    throw new Exception("你和他不是好友，无法发送名片！");
                }

            } else {
                // 群聊发名片
                $groupInfo = Group::getOneByWhere(['tx_code' => $receiveTxCode]);
                if (empty($groupInfo)) {
                    throw new Exception("该群不存在！");
                }

                $groupUserInfo = GroupUser::getOneByWhere(['user_id' => $userId,'group_id' => $groupInfo['id']]);
                if (empty($groupUserInfo)) {
                    throw new Exception("你不是该群成员，无法发送名片！");
                }
            }

            // 4.发送消息
            $imRes = false;
            if ($type == Status::IM_BUSINESS_CARD_SEND_TO_GROUP && isset($groupInfo) && !empty($groupInfo)) {
                // 群聊信息
                // 发送im消息
                $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_SEND_USER_BUSINESS_CARD;
                $publicGroupMessage['tx_code'] = $businessCardUserInfo['tx_code'];
                $publicGroupMessage['nick_name'] = $businessCardUserInfo['nick_name'];
                $publicGroupMessage['face'] = static::getAvatar($businessCardUserInfo['user_face']);
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_SEND_USER_BUSINESS_CARD;
                $publicGroupMessage['time'] = date('Y-m-d H:i:s');
                $imRes = (new Im()) -> sendGroupMessage($groupInfo['tx_code'],$publicGroupMessage, $user['tx_code']);
            }

            // 单聊信息
            if ($type == Status::IM_BUSINESS_CARD_SEND_TO_USER && !empty($userFriendInfo) && isset($userFriendInfo)) {
                $userMessage['message_type'] = Status::MESSAGE_TYPE_SEND_USER_BUSINESS_CARD;
                $userMessage['nick_name'] = $businessCardUserInfo['nick_name'];
                $userMessage['face'] = static::getAvatar($businessCardUserInfo['user_face']);
                $userMessage['tx_code'] = $businessCardUserInfo['tx_code'];
                $userMessage['type'] = Status::MESSAGE_TYPE_SEND_USER_BUSINESS_CARD;
                $userMessage['time'] = date('Y-m-d H:i:s');
                $imRes = (new Im()) -> sendUserMessage($userFriendInfo['friend_tx_code'],$userMessage, $user['tx_code']);
            }

            if (!$imRes) {
                throw new Exception("名片发送异常！");
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '发送成功');

        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(0, $e->getMessage());
        } finally {
            $redis->del(CacheKeys::IM_SEND_BUSINESS_CARD . $userId);
        }
    }

    /**
     * 注销账户
     * @return array
     */
    public function cancellation() {
        $redis = Yii::$app->redis;

        $user = Yii::$app->getUser()->getIdentity()->toArray();
        $userId = $user['id'] ?? 0;
        $trans = static::getDb()->beginTransaction();
        try {
            if (!$userId) {
                throw new Exception('未知用户！');
            }

            // 判断该用户是否被封禁
            UserUnusualLog::checkUserUnusual($user['id'],Status::USER_UNUSUAL_TYPE_CIRCLE);

            // 注销用户
            $args['user'] = $user;
            $args['user_id'] = $userId;
            Yii::$app->queue->push(new \common\queue\User($args));

            $trans->commit();
            return Functions::formatRestAPI(0, '正在注销中，请稍等...');

        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(0, $e->getMessage());
        } finally {
            $redis->del(CacheKeys::IM_SEND_BUSINESS_CARD . $userId);
        }
    }

    /**
     * 获取附近用户列表
     * @return array
     */
    public function getNearby(){
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',20);
            $sex = (int) Yii::$app->request->get('sex','');
            $where = $andWhere = [];

            if($sex){
                $where['sex'] = $sex;
            }

            $levelInfo = UserLevel::getOneByWhere(['id' => $user['level_id']]);

            // 相同喜好
            #1.按照距离排序
            #2.按照性别排序
//            $where['is_setting'] = Status::COMMON_RADIO_YES;
//            switch ($user['sex']) {
//                case Status::COMMON_SEX_MAN:
//                    $where['sex'] = Status::COMMON_SEX_WOMAN;
//                    break;
//                case Status::COMMON_SEX_WOMAN:
//                    $where['sex'] = Status::COMMON_SEX_MAN;
//                    break;
//                default:
//                    break;
//            }

//            $andWhere[] = ['<>','id',$user['id']];
//            $startAge = date('Y-m-d',strtotime('-5 years', strtotime($user['birthday'])));
//            $endAge = date('Y-m-d',strtotime('+5 years', strtotime($user['birthday'])));
//            $andWhere[] = ['between','birthday', $startAge, $endAge];

//            $interestArr = array_filter(explode(',',trim($user['interests'],',')));
//            foreach ($interestArr as $value) {
//                $andWhere[] = ['like','interests', $value.','];
//            }

            list($longitude,$latitude) = $this->getPosition($user['phone']);

            $distanceField = "ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (
                                    {$latitude} * PI() / 180 - latitude * PI() / 180
                                ) / 2
                            ),
                            2
                        ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                            SIN(
                                (
                                    {$longitude} * PI() / 180 - longitude * PI() / 180
                                ) / 2
                            ),
                            2
                        )
                    )
                ),5 
            ) AS distance";

            // 过滤掉已注销的用户
            $closeUserList = User::getByAndWhere(['is_delete' => 2 , 'status' => 2]);
            $closeIds = array_column($closeUserList,'id');

            if ($closeIds) {
                $andWhere[] = ['not in','id',$closeIds];
            }

            $count = static::getCountByAndWhere($where,$andWhere);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $orderSql = "distance ASC, is_setting ASC";
            $list = static::getObjectByAndWhere($where,$andWhere, ['id','nick_name','user_face','tx_code','qr_code','signature','sex','birthday','interests','is_hiding',$distanceField], $orderSql, $offset, $size)->with()->asArray()->all();

            // 查询在线状态
            $onLineResult = $list ? (new Im()) -> queryOnlineStatus(ArrayHelper::getColumn($list,'tx_code')) : [];
            $result = [];

            foreach ($list as $k => $v) {
                $tmp = [
                    'nick_name' => $v['nick_name'] ?? '',
                    'face' => static::getAvatar($v['user_face']),
                    'tx_code' => $v['tx_code'] ?: '',
                    'sex' => (int) $v['sex'],
                    'age' => $v['birthday'] ? Functions::birthday($v['birthday']) : 0,
                    'distance' => round($v['distance'],2),
                    'signature' => $v['signature'] ?: '暂无签名',
                    'is_online' => false,
                ];

                $tmp['distance'] = static::handleDistance($levelInfo, $v, $tmp['distance']);


//                if($levelInfo['show_nearby'] == Status::COMMON_RADIO_NO ){
//                    $tmp['distance'] = ">100KM";
//                } else {
////                    $tmp['distance'] = $tmp['distance'] ? $tmp['distance'].'KM' : '未知';
//                    $tmp['distance'] = $tmp['distance'].'KM';
//                }

                if ($onLineResult) {
                    foreach ($onLineResult as $kk => $vv) {
                        if ($vv['To_Account'] == $v['tx_code']) {
                            $tmp['is_online'] = $vv['Status'] == 'Online' ? true : false;
                            continue;
                        }
                    }
                }

                $result[] = $tmp;
            }
            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取附近用户列表
     * @return array
     */
    public function getViewList(){
        try {
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            $levelInfo = UserLevel::getOneByWhere(['id' => $userInfo['level_id']]);
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',20);
            $where = [];

            $where['view_user'] = $userInfo['id'];

            $count = UserViewLog::getObjectByWhere($where)->count();
            $data = UserViewLog::setPageinationAPI($page, $size, $count);

//            $longitude = $this->getLongitude() ? $this->getLongitude() : '116.3424590000';
//            $latitude = $this->getLatitude() ? $this->getLatitude() : '39.91024';

            list($longitude,$latitude) = $this->getPosition($userInfo['phone']);


            $offset = ($page - 1) * $size;
            $orderSql = "view_time DESC";
            $list = UserViewLog::getObjectByWhere($where, ['*'], $orderSql, $offset, $size)
//                ->groupBy('user_id')
                ->with([
                    'user' => function ($q) use ($longitude, $latitude) {
                        $distanceField = "ROUND(
                        6378.138 * 2 * ASIN(
                            SQRT(
                                POW(
                                    SIN(
                                        (
                                            {$latitude} * PI() / 180 - latitude * PI() / 180
                                        ) / 2
                                    ),
                                    2
                                ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                                    SIN(
                                        (
                                            {$longitude} * PI() / 180 - longitude * PI() / 180
                                        ) / 2
                                    ),
                                    2
                                )
                            )
                        ),5 
                    ) AS distance";
                        $q -> select(['id','nick_name','tx_code','signature','user_face','latitude','longitude','is_hiding',$distanceField]);
                    },
                    'view',
//                    'log'=>function($q){
//                        $q -> select(['*'])
//                            ->orderBy('view_time DESC');
//                    }
                ])
                ->asArray()
                ->all();

            //关注的人
            $followList = UserAttention::getByAndWhere(['user_id'=>$userInfo['id'],'type'=>Status::USER_ATTENTION_TYPE_FOLLOW]);
            $followIds = array_column($followList,'topic_id');

            $result = [];
            foreach ($list as $k => $v) {
                $singleUserInfo = ArrayHelper::getValue($v,'user',[]);
//                $logInfo = ArrayHelper::getValue($v,'log',[]);
                $tmp = [
                    'id' => (int) $v['id'],
                    'user_id' => $singleUserInfo['id'] ?: '',
                    'tx_code' => $singleUserInfo['tx_code'] ?: '',
                    'nick_name' => $singleUserInfo['nick_name'] ?? '',
                    'signature' => $singleUserInfo['signature'],
                    'face' => static::getAvatar($singleUserInfo['user_face']),
//                    'time' => $logInfo['view_time'],
                    'time' => $v['view_time'],
                    'is_attention' => in_array($v['user_id'],$followIds),
                    'distance' => round($singleUserInfo['distance'],2),
                ];

                $tmp['distance'] = static::handleDistance($levelInfo, $singleUserInfo, $tmp['distance']);


//                if($levelInfo['show_nearby'] == Status::COMMON_RADIO_NO ){
//                    $tmp['distance'] = ">100KM";
//                } else {
////                    $tmp['distance'] = $tmp['distance'] ? $tmp['distance'].'KM' : '未知';
//                    $tmp['distance'] = $tmp['distance'].'KM';
//                }

                $result[] = $tmp;
            }
            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        }
        catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        }
        catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    // 处理显示距离
    public static function handleDistance($levelInfo = [], $userInfo = [], $distance = 0) {
        $returnDistance = $distance;
        if($levelInfo && $levelInfo['show_nearby'] == Status::COMMON_RADIO_NO && $userInfo['is_hiding'] == Status::COMMON_RADIO_NO){
            $returnDistance = ">100KM";
        } else {
            $returnDistance = $distance.'KM';
        }
        if ($userInfo['is_hiding'] == Status::COMMON_RADIO_YES) {
            $returnDistance = '未知';
        }

        return $returnDistance;
    }
}
